import axios from 'axios';
import app from '@/utils/index'
// import { getToken } from '@/utils/auth'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
});
// 请求拦截
service.interceptors.request.use(config => {
  const TOKEN = app.getStorage('Token');
  console.log('14...', TOKEN);
  if(TOKEN) {
    config.headers['Authorization'] = 'Bearer '+ TOKEN.data;
  }

  if(config.method === 'get' && config.params) {
    let url = config.url +'?',
      tmpArr = Object.keys(config.params),
      len = tmpArr.length;
    tmpArr.map((item, index) => {
      const v = config.params[item];
      let  query = encodeURIComponent(item) +'=';
      if(app.hasValue(v)) {
        url += query + encodeURIComponent(v) + index < len ? '&' : '';
      }
    })
    // config.params = {};
    config.url = url;
  }
  return config;
}, err => {
  Promise.reject(err);
})

// 响应拦截
service.interceptors.response.use(response => {
  const code = response.data.code || 200,
        msg = response.data.msg;
  if(code !== 200) return Promise.reject(new Error(msg));
  if(code === 401) {
    console.log('44...');
    this.store.dispatch('SET_UINFO', '');
    location.href = '/';
  }
  return response;
}, err => {
  return Promise.reject(err);
})

export default service;